package controller.room
{
	import events.room.EventAddItemToRoom;
	
	import flash.geom.Point;
	
	import model.ModelProject;
	
	import org.flashIso.engine.base.IsoRoom;
	import org.flashIso.engine.core.Point2D;
	import org.flashIso.engine.core.Point3D;
	import org.flashIso.engine.library.objects.LBase;
	import org.flashIso.engine.library.objects.LObject;
	import org.flashIso.engine.library.objects.LTile;
	import org.flashIso.engine.objects.IsoObject;
	import org.flashIso.engine.objects.IsoTile;
	import org.robotlegs.mvcs.Command;
	
	public class CommandAddItemToRoom extends Command
	{
		[Inject]
		public var e:EventAddItemToRoom;
		
		[Inject]
		public var mp:ModelProject;
		
		override public function execute() : void {
			mp.projectModified = true;
			
			var p:Point = e.globalCoordinates.clone();
			var room:IsoRoom = e.room;
			var item:LBase = e.item;
			p = room.globalToLocal(p);
			var p2d:Point2D = new Point2D(p.x, p.y);
			var p3d:Point3D = room.map.perspective.get3DCoordinates(p2d);
			if (item is LTile){
				var cell:Point2D = room.map.getCellAtCoordinates(p3d);
				trace("cell: " + cell);
				var oldTile:IsoTile = room.map.getTileAtCell(cell);
				if (oldTile == null || (oldTile.libraryReference != item)){
					var tile:IsoTile = new IsoTile();
					tile.libraryReference = (item as LTile);
					tile.cell = cell;
					room.map.addElement(tile);
				}
			}else
			if (item is LObject){
				var object:IsoObject = new IsoObject();
				object.libraryReference = item as LObject;
				object.position = p3d;
				room.map.addElement(object);
			}else{
				throw(new Error("Unknown item type!"));
			}
		}
	}
}